import 'package:get/get.dart';
import '../../../data/services/api_service.dart';

class OrderListController extends GetxController {
  // 服务实例 - GetX规范
  final ApiService _apiService = Get.find<ApiService>();

  // 响应式变量
  final _isLoading = false.obs;
  final _orderList = <CloudStorageOrder>[].obs;
  final _currentPage = 1.obs;
  final _totalPages = 0.obs;
  final _hasMore = true.obs;

  // Getters
  bool get isLoading => _isLoading.value;
  List<CloudStorageOrder> get orderList => _orderList;
  int get currentPage => _currentPage.value;
  int get totalPages => _totalPages.value;
  bool get hasMore => _hasMore.value;

  @override
  void onReady() {
    super.onReady();
    // 页面准备好后加载订单数据
    loadOrders();
  }

  /// 加载订单列表
  Future<void> loadOrders({bool refresh = false}) async {
    if (_isLoading.value) return;

    try {
      _isLoading.value = true;

      // 如果是刷新，重置分页
      if (refresh) {
        _currentPage.value = 1;
        _orderList.clear();
      }

      print('🛒 开始获取订单列表，页码：${_currentPage.value}');

      final response = await _apiService.getCloudStorageOrders(
        pageNo: _currentPage.value,
        pageSize: 10,
        status: 9, // 9:全部
      );

      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        final records = data['records'] as List<dynamic>?;
        final total = data['total'] as int? ?? 0;
        final pages = data['pages'] as int? ?? 0;

        _totalPages.value = pages;

        if (records != null) {
          final newOrders =
              records
                  .where((item) => item is Map<String, dynamic>)
                  .map((item) => CloudStorageOrder.fromJson(item))
                  .toList();

          if (refresh) {
            _orderList.value = newOrders;
          } else {
            _orderList.addAll(newOrders);
          }

          // 判断是否还有更多数据
          _hasMore.value = _currentPage.value < _totalPages.value;

          print('✅ 订单列表获取成功，本页${newOrders.length}条，总计${total}条');
        }
      }
    } catch (e) {
      print('❌ 获取订单列表失败: $e');
    } finally {
      _isLoading.value = false;
    }
  }

  /// 加载更多订单
  Future<void> loadMoreOrders() async {
    if (!_hasMore.value || _isLoading.value) return;

    _currentPage.value++;
    await loadOrders();
  }

  /// 刷新订单列表
  Future<void> refreshOrders() async {
    await loadOrders(refresh: true);
  }

  /// 获取状态文本
  String getStatusText(int status) {
    switch (status) {
      case 0:
        return '未生效';
      case 1:
        return '生效中';
      case 2:
        return '暂停';
      case 3:
        return '已失效';
      default:
        return '未知状态';
    }
  }

  /// 获取状态颜色
  int getStatusColor(int status) {
    switch (status) {
      case 0:
        return 0xFF999999; // 未生效：灰色
      case 1:
        return 0xFF127FFF; // 生效中：蓝色
      case 2:
        return 0xFFFF8C00; // 暂停：橙色
      case 3:
        return 0xFF666666; // 已失效：深灰色
      default:
        return 0xFF999999;
    }
  }

  /// 获取云存类型文本
  String getCloudStorageTypeText(int type) {
    switch (type) {
      case 1:
        return '全天录像';
      case 2:
        return '报警时录像';
      default:
        return '未知类型';
    }
  }
}

/// 云存订单数据模型
class CloudStorageOrder {
  final int id;
  final String channelId;
  final String channelName;
  final String deviceId;
  final int cloudStorageDuration;
  final int cloudStorageType;
  final int cloudStorageStream;
  final String customerName;
  final int status;
  final String? enableStartAt;
  final String? enableEndAt;
  final String createdAt;
  final String updatedAt;

  CloudStorageOrder({
    required this.id,
    required this.channelId,
    required this.channelName,
    required this.deviceId,
    required this.cloudStorageDuration,
    required this.cloudStorageType,
    required this.cloudStorageStream,
    required this.customerName,
    required this.status,
    this.enableStartAt,
    this.enableEndAt,
    required this.createdAt,
    required this.updatedAt,
  });

  factory CloudStorageOrder.fromJson(Map<String, dynamic> json) {
    return CloudStorageOrder(
      id: json['id'] as int? ?? 0,
      channelId: json['channelId']?.toString() ?? '',
      channelName: json['channelName']?.toString() ?? '',
      deviceId: json['deviceId']?.toString() ?? '',
      cloudStorageDuration: json['cloudStorageDuration'] as int? ?? 0,
      cloudStorageType: json['cloudStorageType'] as int? ?? 1,
      cloudStorageStream: json['cloudStorageStream'] as int? ?? 2,
      customerName: json['customerName']?.toString() ?? '',
      status: json['status'] as int? ?? 0,
      enableStartAt: json['enableStartAt']?.toString(),
      enableEndAt: json['enableEndAt']?.toString(),
      createdAt: json['createdAt']?.toString() ?? '',
      updatedAt: json['updatedAt']?.toString() ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'channelId': channelId,
      'channelName': channelName,
      'deviceId': deviceId,
      'cloudStorageDuration': cloudStorageDuration,
      'cloudStorageType': cloudStorageType,
      'cloudStorageStream': cloudStorageStream,
      'customerName': customerName,
      'status': status,
      'enableStartAt': enableStartAt,
      'enableEndAt': enableEndAt,
      'createdAt': createdAt,
      'updatedAt': updatedAt,
    };
  }
}
